package com.sy.service.impl;

import com.sy.entity.StudyFile;
import com.sy.entity.Teacher;
import com.sy.service.StudyFileService;
import com.sy.utils.RandomUtils;
import com.sy.vo.StudyFileVo;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Part;
import java.io.*;
import java.net.URLDecoder;

import static com.sy.constant.AppConstant.*;
import static com.sy.constant.AppConstant.FILE_EXTENSION_JPEG;


@Service
public class StudyFileServiceImpl extends BaseServiceImpl implements StudyFileService {
    public StudyFileServiceImpl(){
    }

    @Override
    public StudyFile uploadOneFile(Integer id,Part part) throws IOException, ServletException {
        StudyFileVo uploadFileVo = new StudyFileVo();

        //1、获取上传的文件对应的信息,入参为前端传递文件的时候文件二进制数据对应的参数名
//        Part part = req.getPart("file");
        //2、将获取到的文件信息保存到服务器硬盘上
        //(1)判断要上传文件的目录是否存在，不存在则创建之
        Teacher teacher = teacherMapper.getTeacherById(String.valueOf(id));
        Integer workno = teacher.getWorkno();
        //拼接上传文件地址，后带老师的工号
        String filePath = UPLOAD_DIR_PATH + workno + File.separator;
        File uploadDir = new File(filePath);
        if(!uploadDir.exists()){
            uploadDir.mkdirs();
        }
        //(2)为了防止上传目录中文件出现重名的问题，对于上传的文件应该要进行重命名
        //在tomcat7 的环境下就没有part.getSubmittedFileName()这一方法，无法直接获取文件名
//        String originalFileName = part.getSubmittedFileName();
        String header = part.getHeader("Content-Disposition");
        //截取不同类型的文件需要自行判断
        //带后缀名
        String originalFileName = header.substring(header.lastIndexOf("=")+2, header.length()-1);
//        String decode1 = URLDecoder.decode(originalFileName, "UTF-8");
//        String str = new String(originalFileName.getBytes("ISO-8859-1"),"UTF-8");
        String fileUUID = RandomUtils.getUuid();

        //获取文件后缀名
        String fileEx = FilenameUtils.getExtension(originalFileName);
        //拼接硬盘中的存储文件名
        String newFileName = fileUUID + "." + fileEx;
        //(3)将文件保存到服务器的硬盘中
        // --流拷贝，将上传时候文件的输入流拷贝到硬盘对应的输出流中
        InputStream is = part.getInputStream();
        String fileSize = String.valueOf(is.available());
        String path = filePath + newFileName;
        FileOutputStream fos = new FileOutputStream(path);
        IOUtils.copy(is, fos);

        //  如果Ajax上传，则应该返回具体的状态
        //  如果上传后的资源需要在页面中回显，则需要返回一个可以直接访问的URL地址

        uploadFileVo.setFileSize(fileSize);
        uploadFileVo.setFilePath(path);
        uploadFileVo.setFileUUID(fileUUID);
        uploadFileVo.setTeacherId(id);
        //将前端编码的文件名解码
        String decode = URLDecoder.decode(originalFileName,"UTF-8");
        uploadFileVo.setFileName(decode);
        //将文件信息插入数据库
        studyFileMapper.insertFile(uploadFileVo);
        //获取刚才插入到数据库中的文件的id
        Integer fileId = uploadFileVo.getId();
        //拼接外网访问url
        String fileUrl ;
//        if(StringUtils.equals(fileEx,FILE_EXTENSION_JPG) || StringUtils.equals(fileEx,FILE_EXTENSION_JPE) || StringUtils.equals(fileEx,FILE_EXTENSION_JPEG)){
//            fileUrl = "%2Ffiles%2F" + fileId + "%3Ftype%3Dpreview%26fileName%3D"+originalFileName+;
//        }else{
//            fileUrl = "%2Ffiles%2F"+fileId+"%3Ftype%3Dpreview%26fileName%3D"+originalFileName+"%26fileEx%3D"+fileEx;
//        }
        fileUrl = "%2Ffiles%2F"+fileId+"%3Ftype%3Dpreview%26fileName%3D"+originalFileName+"%26fileEx%3D"+fileEx;
        System.out.println(fileUrl);
        studyFileMapper.insertFileUrl(fileUrl,fileId);
        return studyFileMapper.getStudyFile(fileId);
    }

    @Override
    public StudyFile getFile(String id,ServletOutputStream os) throws IOException {
        StudyFile studyFile = studyFileMapper.getStudyFile(Integer.parseInt(id));
        String filePath = studyFile.getFilePath();
        // 构建要输出给客户端的数据
        File file = new File(filePath);
        // 典型的流操作代码
        FileInputStream fis = new FileInputStream(file);
        IOUtils.copy(fis,os);
        return studyFile;
    }

    @Override
    public boolean deleteStudyFile(String fileId) {
        return studyFileMapper.deleteStudyFile(fileId);
    }
}
